package com.baseManage.core.taglib;

import com.jfinal.template.io.Writer;
import java.util.Map;

import com.baseManage.model.SysUser;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * 使用jf模板引擎扩展指令构造系统左侧菜单，代替jstl自定义标签的实现方式
 */
public class ButtonDirective extends Directive {

	private String userId = "";// 用户id

	private String btnId = "";// 按钮id属性值

	private String className = "";// 按钮class名称
	/**
	 * 需要的权限(按钮跳转地址)
	 */
	private String permission = "";// 按钮跳转路径

	private String style = "";// 按钮自定义样式

	private String btnName = "";// 按钮name属性值

	private String btnValue = "";// 按钮value属性值

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		boolean hasAuth = true;
		// 表达式必须通过exprList.eval(scope)求值，返回的数据形式与前端传递的数据格式一致
		Map<String, Object> params = (Map<String, Object>) exprList.eval(scope);
		if (params.get("permission") != null && params.get("userId") == null) {
			throw new ParseException("按钮需要权限控制，请传入userId属性", location);
		}
		if (params.get("userId") != null) {
			userId = String.valueOf(params.get("userId"));
		}
		if (params.get("btnId") != null) {
			btnId = params.get("btnId").toString();
		}
		if (params.get("className") != null) {
			className = params.get("className").toString();
		}
		if (params.get("permission") != null) {
			permission = params.get("permission").toString();
		}
		if (params.get("style") != null) {
			style = params.get("style").toString();
		}
		if (params.get("btnName") != null) {
			btnName = params.get("btnName").toString();
		}
		if (params.get("btnValue") != null) {
			btnValue = params.get("btnValue").toString();
		}
		StringBuffer button = new StringBuffer("");
		if (StrKit.notBlank(permission)) {
			SysUser curUser = SysUser.dao.findById(userId);
			if (curUser == null || !curUser.getPermissionSets().contains(permission)) {
				hasAuth = false;
			}
		}
		if (hasAuth) {
			button.append("<input type=\"button\"");
			if (StrKit.notBlank(className)) {
				button.append(" class=\"" + className + "\"");
			}
			if (StrKit.notBlank(btnId)) {
				button.append(" id=\"" + btnId + "\"");
			}
			if (StrKit.notBlank(btnName)) {
				button.append(" name=\"" + btnName + "\"");
			}
			if (StrKit.notBlank(style)) {
				button.append(" style=\"" + style + "\"");
			}
			if (StrKit.notBlank(btnValue)) {
				button.append(" value=\"" + btnValue + "\"");
			}
			button.append("/>\n");
		}
		write(writer, button.toString());
	}
}
